import { Breadcrumb, Cascader, message } from 'antd';
import React, { FC } from 'react';
import {
  FormPanel,
  MinioUploadListType,
  ExtendReader,
  FormPanelStatus,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
  type FormPanelObject,
  Utils,
  InputType,
} from 'lfun-bg-comp';
//import { useNavigate } from 'react-router-dom';
import { PageContainer } from '@/component/page-container';
import SearchInput from '@/view/component/searchInput';
import { GENDER } from '@/constant/basicOptions';
import { ETHNICITIES } from '@/constant/ethnicity';
import {
  SearchStuInfo,
  TransferinFromoutsideInfo,
  getStuBaseInfo,
  getStuInfo,
  getStudentkeyinfo,
  transferin,
  transferinFromoutside,
} from '@/service/student/instudent';
import { ID_TYPE } from '@/constant/studentOptions';
import { searchSchoolByName } from '@/service/unit/school';
import styles from './index.less';
import {
  getClassesOptions,
  getCountryOptions,
  getGradesOptions,
  getMajorOptions,
  getMajorOptionsBySchool,
  getProvinceCityOptions,
  getSchoolOptions,
  getSessionOptions,
} from '@/service/options';
import useCountry from '@/hooks/useCountry';

const Groups: FC = () => {
  //const navigate = useNavigate();
  const [values, setValues] = React.useState<any>({});
  const [sysIn, setSysIn] = React.useState(null);
  const [baseInfoForm, setBaseInfoForm] = React.useState<any>();
  const [outInfoForm, setOutInfoForm] = React.useState<any>();
  const [inInfoForm, setInInfoForm] = React.useState<any>();
  const country = useCountry();

  const list = [
    {
      title: '学生查询',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '姓名',
          name: 'student_name',
          key: 'student_name',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '证件类型',
          name: 'id_type',
          key: 'id_type',
          relationFields: ['id_number'],
          required: true,
          inputType: InputType.select,
          renderOption: ID_TYPE,
        },
        {
          label: '证件号码',
          name: 'id_number',
          key: 'id_number',
          required: true,
          textRange: [0, 30],
          ruleType: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('id_type');
            if (id_type === 'resident_id_card') {
              return 'cnPeopleNo';
            }
            return '';
          },
        },
      ],
    },
  ];
  const baiscInfoList = [
    {
      title: '学生基本信息',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '姓名',
          name: 'student_name',
          key: 'student_name',
          required: true,
          textRange: [0, 10],
        },
        {
          label: '性别',
          name: 'student_gender',
          key: 'student_gender',
          relationFields: ['id_number'],
          required: true,
          inputType: InputType.select,
          renderOption: GENDER,
          render: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('id_type');
            if (id_type !== 'resident_id_card') {
              return formObjectPanel.getFieldValue('student_gender');
            }
            return ExtendReader.renderGender('id_number', 'student_gender', formObjectPanel);
          },
        },
        {
          label: '民族',
          name: 'ethnicity',
          key: 'ethnicity',
          required: true,
          inputType: InputType.select,
          renderOption: ETHNICITIES,
        },
        {
          label: '证件类型',
          name: 'id_type',
          key: 'id_type',
          required: true,
          relationFields: ['id_number'],
          inputType: InputType.select,
          renderOption: ID_TYPE,
        },
        {
          label: '证件号码',
          name: 'id_number',
          key: 'id_number',
          required: true,
          relationFields: ['birthday', 'student_gender'],
          textRange: [0, 30],
          ruleType: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('id_type');
            if (id_type === 'resident_id_card') {
              return 'cnPeopleNo';
            }
            return '';
          },
          renderValidate: (formOjbectPanel: FormPanelObject) => {
            const id_type = formOjbectPanel.getFieldValue('id_type');
            if (id_type === 'resident_id_card') {
              return ExtendReader.validateCnPeopleNo(
                formOjbectPanel.getFieldValue('id_number'),
                formOjbectPanel.getFieldValue('birthday'),
                formOjbectPanel.getFieldValue('student_gender')
              );
            }
            return '';
          },
        },
        {
          label: '籍贯地行政区',
          name: 'native_place_district',
          key: 'native_place_district',
          required: true,
        },
        {
          label: '学籍号',
          name: 'edu_number',
          key: 'edu_number',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '出生年月',
          name: 'birthday',
          key: 'birthday',
          required: true,
          inputType: InputType.date,
          relationFields: ['id_number'],
          render: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('id_type');
            if (id_type !== 'resident_id_card') {
              return formObjectPanel.getFieldValue('birthday') || values.birthday;
            }
            return ExtendReader.renderBirthday('id_number', 'birthday', formObjectPanel);
          },
        },
        {
          label: '户口所在地（详细）',
          name: 'residence_address_detail',
          key: 'residence_address_detail',
          required: true,
          textRange: [0, 50],
        },
      ],
    },
  ];
  const checkOutList = [
    {
      title: '转出校信息',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '学校省市',
          name: 'province',
          key: 'province',
          required: true,
          inputType: 'children',
          relationFields: ['area_id'],
          children: <Cascader />,
          renderOption: async () => {
            const list = await getProvinceCityOptions();
            return list;
          },
        },
        {
          label: '学校地区',
          name: 'area_id',
          key: 'area_id',
          required: true,
          inputType: InputType.select,
          renderOption: getCountryOptions,
        },
        {
          label: '学校名称',
          name: 'school_id',
          key: 'school_id',
          required: true,
          inputType: InputType.children,
          relationFields: ['grade_id', 'class_id'],
          children: (
            <SearchInput
              onLoadOption={null}
              searchFunction={async v => {
                const res = await searchSchoolByName(v, 1, 100);
                if (res.success) {
                  return res.data.map(item => ({
                    label: item.school_name,
                    value: item.id,
                  }));
                }
                return [];
              }}
              randerOption={option => option}
            />
          ),
        },
        {
          label: '所在届别',
          name: 'session',
          key: 'session',
          required: true,
          inputType: InputType.select,
          renderOption: () => {
            const year = new Date().getFullYear();
            const options = [];
            for (let i = 0; i < 20; i++) {
              options.push({
                label: `${year - i}届`,
                value: `${year - i}届`,
              });
            }
            return options;
          },
        },
        {
          label: '所在年级',
          name: 'grade_name',
          key: 'grade_name',
          required: true,
          inputType: InputType.select,
          renderOption: () => {
            const options = [];
            for (let i = 0; i < 10; i++) {
              options.push({
                label: `${i + 1}年级`,
                value: `${i + 1}年级`,
              });
            }
            return options;
          },
        },
        {
          label: '所在班级',
          name: 'classes',
          key: 'classes',
          required: true,
          inputType: InputType.select,
          renderOption: () => {
            const options = [];
            for (let i = 0; i < 50; i++) {
              options.push({
                label: `${i + 1}班`,
                value: `${i + 1}班`,
              });
            }
            return options;
          },
        },
        {
          label: '专业方向',
          name: 'major_id',
          key: 'major_id',
          required: true,
          inputType: InputType.children,
          children: <Cascader />,
          hidden: Utils.getProps('edu_type') !== 'vocational',
          formatSubmitValue: (value: string[]) => {
            if (value && value.length && value.length > 0) return value.join(',');
            return value;
          },
          renderOption: async () => {
            const list = await getMajorOptions();
            return list;
          },
        },
      ],
    },
  ];
  const noSysCheckOutList = [
    {
      title: '转出校信息',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '学校省市',
          name: 'province',
          key: 'province',
          required: true,
          inputType: 'children',
          relationFields: ['area_id'],
          children: <Cascader />,
          renderOption: async () => {
            const list = await getProvinceCityOptions();
            return list;
          },
        },
        {
          label: '学校地区',
          name: 'area_id',
          key: 'area_id',
          required: true,
          inputType: InputType.select,
          renderOption: getCountryOptions,
        },
        {
          label: '学校名称',
          name: 'school_id',
          key: 'school_id',
          required: true,
        },
        {
          label: '所在届别',
          name: 'session',
          key: 'session',
          required: true,
        },
        {
          label: '所在年级',
          name: 'grade_name',
          key: 'grade_name',
          required: true,
        },
        {
          label: '所在班级',
          name: 'classes',
          key: 'classes',
          required: true,
        },
        {
          label: '专业方向',
          name: 'major_id',
          key: 'major_id',
          required: true,
          hidden: Utils.getProps('edu_type') !== 'vocational',
        },
      ],
    },
  ];
  const nonEditcheckOutList = [
    {
      title: '转出校信息',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '学校省市',
          name: 'province',
          key: 'province',
          required: true,
          inputType: InputType.children,
          relationFields: ['block'],
          children: <Cascader />,
          renderOption: async () => {
            const list = await getProvinceCityOptions();
            return list;
          },
        },
        {
          label: '学校地区',
          name: 'block',
          key: 'block',
          required: true,
          inputType: InputType.select,
          // renderOption: async (form, values) => {
          //   const list = await getCountryOptions(form, values);
          //   return list;
          // },
          renderOption: country,
        },
        {
          label: '学校名称',
          name: 'school_name',
          key: 'school_name',
        },
        {
          label: '所在届别',
          name: 'session',
          key: 'session',
        },
        {
          label: '所在年级',
          name: 'grade_id',
          key: 'grade_id',
          relationFields: ['class_id'],
          required: true,
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) => {
            const list = await getGradesOptions(form);
            return list;
          },
        },
        {
          label: '所在班级',
          name: 'class_id',
          key: 'class_id',
          required: true,
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) => {
            const list = await getClassesOptions(form);
            return list;
          },
        },
        {
          label: '专业方向',
          name: 'major_name',
          key: 'major_name',
          inputType: InputType.children,
          children: <Cascader />,
          hidden: Utils.getProps('edu_type') !== 'vocational',
          formatSubmitValue: (value: string[]) => {
            if (value && value.length && value.length > 0) return value.join(',');
            return value;
          },
        },
      ],
    },
  ];
  const checkInList = [
    {
      title: '转入校信息',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '学校省市',
          name: 'province',
          key: 'province',
          inputType: InputType.children,
          relationFields: ['area_id'],
          children: <Cascader />,
          renderOption: async () => {
            const list = await getProvinceCityOptions();
            return list;
          },
        },
        {
          label: '学校地区',
          name: 'area_id',
          key: 'area_id',
          required: true,
          inputType: InputType.select,
          relationFields: ['school_id'],
          renderOption: async (form: FormPanelObject) => {
            const list = await getCountryOptions(form);
            return list;
          },
        },
        // {
        //   label: '学校名称',
        //   name: 'school_id',
        //   key: 'school_id',
        //   required: true,
        //   relationFields: ['grade_id', 'major_id'],
        //   inputType: InputType.select,
        //   renderOption: async (form: FormPanelObject) => {
        //     console.log(999);

        //     const list = await getSchoolOptions(form);
        //     return list;
        //   },
        // },
        {
          label: '学校名称',
          name: 'school_id',
          key: 'school_id',
          required: true,
          inputType: InputType.children,
          relationFields: ['grade_id', 'class_id'],
          children: (
            <SearchInput
              onLoadOption={null}
              searchFunction={async v => {
                const res = await searchSchoolByName(v, 1, 100);
                if (res.success) {
                  return res.data.map(item => ({
                    label: item.school_name,
                    value: item.id,
                  }));
                }
                return [];
              }}
              randerOption={option => option}
            />
          ),
        },
        {
          label: '转入时间',
          name: 'transfer_time',
          key: 'transfer_time',
          required: true,
          inputType: InputType.date,
        },
        {
          label: '所在届别',
          name: 'session',
          key: 'session',
          required: true,
          inputType: InputType.select,
          renderOption: async () => {
            const list = await getSessionOptions();
            return list;
          },
        },
        // // {
        // //   label: '附设班',
        // //   name: 'attchClass',
        // //   key: 'attchClass',
        // //   required: true,
        // //   inputType: 'select',
        // //   inputProps: {
        // //     placeholder: '请选择',
        // //     allowClear: true,
        // //     showSearch: true,
        // //     filterOption: utils.filterOption,
        // //   },
        // //   renderOption: [],
        // // },
        {
          label: '所在年级',
          name: 'grade_id',
          key: 'grade_id',
          relationFields: ['class_id'],
          required: true,
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) => {
            const list = await getGradesOptions(form);
            return list;
          },
        },
        {
          label: '所在班级',
          name: 'class_id',
          key: 'class_id',
          required: true,
          inputType: InputType.select,
          renderOption: async (form: FormPanelObject) => {
            const list = await getClassesOptions(form);
            return list;
          },
        },
        {
          label: '专业方向',
          name: 'major_id',
          key: 'major_id',
          required: true,
          hidden: Utils.getProps('edu_type') !== 'vocational',
          inputType: InputType.children,
          children: <Cascader />,
          renderOption: async (form: FormPanelObject) => {
            const list = await getMajorOptionsBySchool(form);
            return list;
          },
          formatSubmitValue: (value: string[]) => {
            if (value && value.length && value.length > 0) return value.join(',');
            return value;
          },
        },
        {
          label: '备注',
          name: 'transfer_reason',
          key: 'transfer_reason',
          span: 24,
          props: {
            labelCol: { span: 2 },
            wrapperCol: { span: 20 },
          },
          inputType: InputType.textarea,
        },
        {
          label: '上传附件',
          name: 'doc_upload',
          key: 'doc_upload',
          span: 24,
          props: {
            labelCol: { span: 2 },
            wrapperCol: { span: 20 },
          },
          inputType: 'minioUpload',
          inputProps: {
            listType: MinioUploadListType.picture,
            text: '浏览',
            placeholder: '请上传附件为图片格式（.png/.jpg）',
            maxCount: 1,
            uploadSrv: '/school/v1/storage/school-upload-uri',
          },
          formatSubmitValue: (value: string) => {
            if (value === undefined || value === 'undefined') return '';
            return value;
          },
        },
      ],
    },
  ];

  const saveBySysout = async () => {
    const saveparams: TransferinFromoutsideInfo = {
      student_baseinfo: {
        ...baseInfoForm.formPanelObject.getFieldsValue(),
        birthday: baseInfoForm.formPanelObject.getFieldValue('birthday').format('YYYY-MM-DD'),
      },
      student_edu_info_in: {
        ...inInfoForm.formPanelObject.getFieldsValue(),
        doc_upload: inInfoForm.formPanelObject.getFieldValue('doc_upload')
          ? String(inInfoForm.formPanelObject.getFieldValue('doc_upload')[0].uid)
          : '',
        major_id: inInfoForm.formPanelObject.getFieldValue('major_id'),
        province_id: inInfoForm.formPanelObject.getFieldValue('province')[0],
        city_id: inInfoForm.formPanelObject.getFieldValue('province')[1],
        transfer_time: inInfoForm.formPanelObject.getFieldValue('transfer_time').format('YYYY-MM-DD'),
      },
      student_edu_info_out: {
        ...outInfoForm.formPanelObject.getFieldsValue(),
        province_id: outInfoForm.formPanelObject.getFieldValue('province')[0],
        city_id: outInfoForm.formPanelObject.getFieldValue('province')[1],
        major_id: outInfoForm.formPanelObject.getFieldValue('major_id'),
      },
    };
    const r = await transferinFromoutside(saveparams);
    if (r.success) {
      message.success('提交成功');
      setValues({});
      baseInfoForm.formPanelObject.resetFields();
      outInfoForm.formPanelObject.resetFields();
      inInfoForm.formPanelObject.resetFields();
    } else {
      baseInfoForm.formPanelObject.reVaildation(r);
      outInfoForm.formPanelObject.reVaildation(r);
      inInfoForm.formPanelObject.reVaildation(r);
    }
  };

  return (
    <PageContainer header={<Breadcrumb items={[{ title: '发起转入' }]} />}>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        template={list}
        onReset={(formPanelObject: FormPanelObject) => {
          formPanelObject.resetFields();
          setSysIn(null);
        }}
        onFinish={async (formPanelObject: FormPanelObject) => {
          const values = formPanelObject.getFieldsValue();
          console.log('🚀 ~ onFinish={ ~ values:', values);
          const searchval: SearchStuInfo = {
            ...values,
          };
          const r = await getStuInfo(searchval);
          if (r.success) {
            if (r.data && r.data.items.length > 0) {
              const baseInfo = await getStuBaseInfo(r.data.items[0].student_id);
              const keyInfo = await getStudentkeyinfo(r.data.items[0].student_id);
              keyInfo.data.province = [keyInfo.data.province || '210000', keyInfo.data.city || '210100'];
              setValues({ ...r.data.items[0], ...baseInfo.data, ...keyInfo.data });
              setSysIn(true);
            } else {
              const idCard = Utils.chineseIDCard(values.id_number);
              setValues({
                ...values,
                student_gender: idCard.isValid ? (idCard.gender === 1 ? 'male' : 'female') : '',
                birthday: idCard.isValid
                  ? `${idCard?.birth.slice(0, 4)}-${idCard?.birth.slice(4, 6)}-${idCard?.birth.slice(6, 8)}`
                  : '',
              });
              setSysIn(false);
            }
          } else {
            formPanelObject.reVaildation(r);
          }
        }}
      />
      <span className={styles.checkinNonstuTip}>
        {sysIn === false ? '该生不在系统中，完善以下信息，继续转学流程' : ''}
      </span>

      <FormPanel
        template={baiscInfoList}
        formStatus={sysIn ? FormPanelStatus.nonEdit : FormPanelStatus.edit}
        buttonsDisplay={FormPanelBtnDisplay.none}
        onLoad={(formPanelObject: FormPanelObject) => {
          setBaseInfoForm({ formPanelObject });
        }}
        values={values}
        onValuesChange={sv => {
          setValues(sv);
        }}
      />
      {typeof sysIn === 'boolean' && sysIn ? (
        <FormPanel
          template={nonEditcheckOutList}
          values={values}
          formStatus={FormPanelStatus.nonEdit}
          buttonsDisplay={FormPanelBtnDisplay.none}
        />
      ) : (
        <FormPanel
          key="setOutInfoForm"
          template={sysIn !== false ? checkOutList : noSysCheckOutList}
          onLoad={(formPanelObject: FormPanelObject) => {
            setOutInfoForm({ formPanelObject });
          }}
          buttonsDisplay="none"
        />
      )}

      <FormPanel
        btnsAlign={FormPanelBtnAlign.center}
        restBtnText="取消"
        submitBtnText="提交"
        buttonsDisplay={FormPanelBtnDisplay.block}
        values={{ province: ['210000', '210100'] }}
        template={checkInList}
        onReset={(formPanelObject: FormPanelObject) => {
          formPanelObject.resetFields();
          baseInfoForm.formPanelObject.resetFields();
          outInfoForm.formPanelObject.resetFields();
          inInfoForm.formPanelObject.resetFields();
          setSysIn(null);
        }}
        onLoad={(formPanelObject: FormPanelObject) => {
          setInInfoForm({ formPanelObject });
        }}
        onFinishing={() => {
          // if (typeof sysIn !== 'boolean') {
          //   message.info('请先获取学生信息');
          //   return false;
          // }
          if (sysIn) {
            return true;
          }
          baseInfoForm.formPanelObject
            .validateFields()
            .then(() => {
              outInfoForm.formPanelObject
                .validateFields()
                .then(() => {
                  inInfoForm.formPanelObject
                    .validateFields()
                    .then(() => {
                      // 这里写save
                      saveBySysout();
                    })
                    .catch(err => {
                      inInfoForm.formPanelObject.scrollToField(err.errorFields[0].name);
                    });
                })
                .catch(err => {
                  outInfoForm.formPanelObject.scrollToField(err.errorFields[0].name);
                });
            })
            .catch(err => {
              baseInfoForm.formPanelObject.scrollToField(err.errorFields[0].name);
            });
          return false;
        }}
        onFinish={async (formPanelObject: FormPanelObject) => {
          const val = formPanelObject.getFieldsValue();
          if (sysIn) {
            const r = await transferin({
              ...val,
              area_id: val.area_id,
              transfer_time: val.transfer_time.format('YYYY-MM-DD'),
              province_id: val.province[0],
              city_id: val.province[1],
              student_id: values.student_id,
              major_id: val.major_id,
              doc_upload: String((val.doc_upload && val.doc_upload.length ? val.doc_upload[0] : {})?.uid),
            });
            if (r.success) {
              message.success('操作成功');
              setValues({});
              formPanelObject.resetFields();
              baseInfoForm.formPanelObject.resetFields();
              outInfoForm.formPanelObject.resetFields();
              inInfoForm.formPanelObject.resetFields();
              setSysIn(null);
            } else {
              formPanelObject.reVaildation(r);
            }
          }
          return false;
        }}
      />
    </PageContainer>
  );
};

export default Groups;
